using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class Frmw_BuyReturnOutWarehouse : BaseForm1
    {
        private Iw_BuyReturnOutWarehouseServices _w_BuyReturnOutWarehouseServices;
        private Iw_BuyReturnServices _wBuyReturnServices;
        private Iw_BuyReturnDetailServices _w_BuyReturnDetailServices;
        private Iw_BuyReturnOutWarehouseDetailServices _wBuyReturnOutWarehouseDetailServices;
        private Iw_Warehouseervices _w_Warehouseervices;
        public Frmw_BuyReturnOutWarehouse(Iw_BuyReturnOutWarehouseServices w_BuyReturnOutWarehouseServices, Iw_BuyReturnServices wBuyReturnServices, Iw_BuyReturnDetailServices w_BuyReturnDetailServices, Iw_BuyReturnOutWarehouseDetailServices wBuyReturnOutWarehouseDetailServices, Iw_Warehouseervices w_Warehouseervices)
        {
            _w_BuyReturnOutWarehouseServices = w_BuyReturnOutWarehouseServices;
            InitializeComponent();
            _wBuyReturnServices = wBuyReturnServices;
            _w_BuyReturnDetailServices = w_BuyReturnDetailServices;
            _wBuyReturnOutWarehouseDetailServices = wBuyReturnOutWarehouseDetailServices;
            _w_Warehouseervices = w_Warehouseervices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["BuyReturnCode"].HeaderText = "采购退货单号";
            this.dataGridViewList.Columns["BuyCode"].HeaderText = "采购单号";
            this.dataGridViewList.Columns["BuyReturnOutWarehouseCode"].HeaderText = "出库单号";
            this.dataGridViewList.Columns["SupplierCode"].HeaderText = "供应商编码";
            this.dataGridViewList.Columns["SupplierName"].HeaderText = "供应商名称";
            this.dataGridViewList.Columns["InvoicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["InvoicesImage"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["Status"].Visible = false;

            //设置明细 仓库
            Warehouse.DataSource = _w_Warehouseervices.Query();
            Warehouse.DisplayMember = "WarehouseName";
            Warehouse.ValueMember = "WarehouseCode";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_BuyReturnOutWarehouse;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.BuyReturnCode.Text = model.BuyReturnCode;
            this.BuyCode.Text = model.BuyCode;
            this.BuyReturnOutWarehouseCode.Text = model.BuyReturnOutWarehouseCode;
            this.SupplierCode.Text = model.SupplierCode;
            this.SupplierName.Text = model.SupplierName;
            this.InvoicesDate.Text = model.InvoicesDate.ToString();
            this.InvoicesImage.Text = model.InvoicesImage;
            this.Remark.Text = model.Remark;
            this.Status.Text = model.Status;
            SetDataToDetail(GetDetailData(model.BuyReturnOutWarehouseCode));
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SupplierCode.ReadOnly = true;
            SupplierName.ReadOnly = true;
            SetDataGridViewReadonlyStatus();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SupplierCode.ReadOnly = true;
            SupplierName.ReadOnly = true;
            BuyCode.ReadOnly = true;
            BuyReturnCode.ReadOnly = true;
            SetDataGridViewReadonlyStatus();
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_BuyReturnOutWarehouse model = new w_BuyReturnOutWarehouse();
                    // TODO获取界面的数据
                    model.BuyReturnCode = this.BuyReturnCode.Text;
                    model.BuyCode = this.BuyCode.Text;
                    if (string.IsNullOrEmpty(this.BuyReturnOutWarehouseCode.Text))
                    {
                        model.BuyReturnOutWarehouseCode = $"CGTHCK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.BuyReturnOutWarehouseCode = this.BuyReturnOutWarehouseCode.Text;
                    }
                    model.SupplierCode = this.SupplierCode.Text;
                    model.SupplierName = this.SupplierName.Text;
                    model.InvoicesDate = this.InvoicesDate.Value.ToDateTime();
                    model.InvoicesImage = this.InvoicesImage.Tag?.ToString();
                    model.Remark = this.Remark.Text;
                    model.Status = "01";


                    List<w_BuyReturnOutWarehouseDetail> dataDetails = new List<w_BuyReturnOutWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_BuyReturnOutWarehouseDetail detail = new w_BuyReturnOutWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value.ToString();
                            detail.WarehouseName = row.Cells["Warehouse"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.BuyCode = row.Cells["BuyCodeD"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    int id = _w_BuyReturnOutWarehouseServices.AddBuyOutWarehouseInfo(model, dataDetails);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        BuyReturnOutWarehouseCode.Text = model.BuyReturnOutWarehouseCode;
                        SetDataToDetail(GetDetailData(model.BuyReturnOutWarehouseCode));
                    }
                }
                // 修改
                else
                {
                    w_BuyReturnOutWarehouse model = _w_BuyReturnOutWarehouseServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.BuyReturnCode = this.BuyReturnCode.Text;
                    model.BuyCode = this.BuyCode.Text;
                    model.BuyReturnOutWarehouseCode = this.BuyReturnOutWarehouseCode.Text;
                    model.SupplierCode = this.SupplierCode.Text;
                    model.SupplierName = this.SupplierName.Text;
                    model.InvoicesDate = this.InvoicesDate.Value.ToDateTime();
                    model.InvoicesImage = this.InvoicesImage.Tag?.ToString();
                    model.Remark = this.Remark.Text;
                    model.Status = this.Status.Text;

                    List<w_BuyReturnOutWarehouseDetail> dataDetails = new List<w_BuyReturnOutWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_BuyReturnOutWarehouseDetail detail = new w_BuyReturnOutWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value.ToString();
                            detail.WarehouseName = row.Cells["Warehouse"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.BuyCode = row.Cells["BuyCodeD"].FormattedValue.ToString();
                            detail.BuyReturnOutWarehouseDetailCode = row.Cells["BuyReturnOutWarehouseDetailCode"].FormattedValue.ToString();
                            detail.BuyReturnCode = row.Cells["BuyReturnCodeD"].FormattedValue.ToString();
                            detail.BuyReturnOutWarehouseCode = row.Cells["BuyReturnOutWarehouseCodeD"].FormattedValue.ToString();

                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }
                    if (_w_BuyReturnOutWarehouseServices.UpdateBuyOutWarehouseInfo(model, dataDetails))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.BuyReturnOutWarehouseCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(BuyReturnOutWarehouseCode.Text));
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                if (_w_BuyReturnOutWarehouseServices.DeleteBuyOutWarehouseInfo(new w_BuyReturnOutWarehouse()
                {
                    ID = txtID.Text.ToInt32(),
                    BuyReturnOutWarehouseCode = BuyReturnOutWarehouseCode.Text
                }))
                    formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                //列表重新赋值

                dataGridViewDetail.Rows.Clear();
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        //ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            if (string.IsNullOrEmpty(BuyReturnCode.Text))
            {
                MessageBox.Show("采购退货单号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(BuyCode.Text))
            {
                MessageBox.Show("采购单号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(SupplierCode.Text))
            {
                MessageBox.Show("供应商编码不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(SupplierName.Text))
            {
                MessageBox.Show("供应商名称不能为空！");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_BuyReturnOutWarehouse> GetData()
        {
            List<w_BuyReturnOutWarehouse> data = new List<w_BuyReturnOutWarehouse>();
            data = _w_BuyReturnOutWarehouseServices.Query();
            return data;
        }

        private void BuyReturnCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(BuyReturnCode.Text.Trim()))
                {
                    var data = _wBuyReturnServices.QueryByClause(p => p.BuyReturnCode.Equals(BuyReturnCode.Text.Trim()));
                    if (data != null)
                    {
                        SupplierName.Text = data.SupplierName;
                        SupplierCode.Text = data.SupplierCode;

                        BuyCode.Text = data.BuyCode;

                        //明细带出数据

                        List<w_BuyReturnDetail> buyDetails = new List<w_BuyReturnDetail>();
                        buyDetails = _w_BuyReturnDetailServices.QueryListByClause(p => p.BuyReturnCode == data.BuyReturnCode);
                        SetDataToDetail(buyDetails);
                    }
                    else
                    {
                        MessageBox.Show("采购单号不存在！");
                    }
                }
            }
        }
        /// <summary>
        /// 明细表 设置数据 --采购单号带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_BuyReturnDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["Warehouse"].Value = "CK001";
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.ReturnNumber;
                row.Cells["RemarkD"].Value = p.Remark;

                //row.Cells["BuyID"].Value = p.BuyID;
                //row.Cells["BuyCodeD"].Value = p.BuyCode;
                //row.Cells["BuyDetailCode"].Value = p.BuyDetailCode;
            });
        }
        /// <summary>
        /// 明细表 设置数据 --主表带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_BuyReturnOutWarehouseDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.Number;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["Warehouse"].Value = p.WarehouseCode;
                row.Cells["BuyReturnOutWarehouseCodeD"].Value = p.BuyReturnOutWarehouseCode;
                row.Cells["BuyReturnOutWarehouseDetailCode"].Value = p.BuyReturnOutWarehouseDetailCode;
                row.Cells["BuyReturnCodeD"].Value = p.BuyReturnCode;
            });
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_BuyReturnOutWarehouseDetail> GetDetailData(string code)
        {
            List<w_BuyReturnOutWarehouseDetail> data = new List<w_BuyReturnOutWarehouseDetail>();
            data = _wBuyReturnOutWarehouseDetailServices.QueryListByClause(p => p.BuyReturnOutWarehouseCode == code);
            return data;
        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "Number", "Warehouse", "RemarkD" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
    }
}
